package com.bxait.toymail.cart.interceptor;

import com.bxait.com.constant.AuthServerConstant;
import com.bxait.com.constant.CartConstant;
import com.bxait.toymail.cart.vo.UserInfoTo;
import com.bxait.toymail.cart.vo.member.MemberRespVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Chen
 * @description: 自定义拦截器
 * @ClassName CartInterceptor
 * @create 2023-04-22 13:42
 * @Version 1.0
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * @param request
     * @param response
     * @param handler
     * @==============History===============<br/>
     * @Description //  目标方法执行之前
     * @Date 2023/4/22 13:43
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        // 1.在session中尝试获取用户信息
        HttpSession session = request.getSession();
        Object member = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(member != null){
            Map<String, Object> map = objectToMap(member);
            Long id = (Long) map.get("id");
            //用户登录
            userInfoTo.setUserId(id);
            threadLocal.set(userInfoTo);
            return true;
        }

        // 没登录就去登录
        request.getSession().setAttribute("msg","请先进行登录");
        response.sendRedirect("http://auth.toymail.com/login.html");
        return false;



//        // 2.尝试在cookie中获取临时用户信息
//        Cookie[] cookies = request.getCookies();
//        if(cookies!=null && cookies.length>0){
//            for (Cookie cookie : cookies) {
//                String name = cookie.getName();
//                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
//                    userInfoTo.setUserKey(cookie.getValue());
//                    userInfoTo.setTempUser(true);
//                }
//            }
//        }
//
//        // 3.如果cookie中没有临时用户一定要创建一个临时用户
//        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
//            String uuid = UUID.randomUUID().toString();
//            userInfoTo.setUserKey(uuid);
//        }
//        // 4.目标方法执行之前,将这个用户信息保存到本地线程中去
//        threadLocal.set(userInfoTo);
//        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @==============History===============<br/>
     * @Description //  目标方法执行之后
     * @Date 2023/4/22 13:45
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return void
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        UserInfoTo userInfoTo = threadLocal.get();
//        if(!userInfoTo.isTempUser()){
//            // 1.目标方法执行之后,要将临时用户信息保存到cookies中下发给浏览器
//            // 在目标方法执行之前,如果没有临时用户我们创建了一个临时用户,如果有临时用户我们在这个延长这个临时用户的过期时间,相当这一步操作是必须要执行的(spring的看门狗机制)
//            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
//            // 将cookie的作用域放大到父域名,确保各个子域名都能访问到这个cookie
//            cookie.setDomain("toymial.com");
//            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
//            response.addCookie(cookie);
//        }
    }


    /*
     * @param obj
     * @==============History===============<br/>
     * @Description //   object转map
     * @Date 2023/5/7 2023/5/7 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
